package com.cwj.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: Chenwujie
 * @date: 2021-04-06 08:51
 */
public class LockTest {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        // 在try代码块之外获取锁,因为如果放在try代码块内获取锁失败，会导致锁被无故释放。

        Thread thread01 = new Thread("01") {
            @Override
            public void run() {
                lock.lock();
                try {
                    try {
                        condition.await();
                        System.out.println("await");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 业务
                }finally {
                    lock.unlock();
                    System.out.println("unlock1");
                }
            }
        };
        thread01.start();
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Thread thread = new Thread("02") {
            @Override
            public void run() {
                lock.lock();
                try {
                    condition.signal();
                    System.out.println("signal");
                } finally {
                    lock.unlock();
                    System.out.println("unlock2");
                }
            }
        };
        thread.start();
    }
}
